package com.starrysky.cakestore.tags;

import jakarta.servlet.jsp.tagext.TagSupport;
import jakarta.servlet.jsp.JspException;
import java.io.IOException;

public class PaginateTag extends TagSupport {
    private int currentPage;
    private int totalPages;
    private String urlPattern;
    private static final int MAX_VISIBLE_PAGES = 5; // 最多显示的页码数量

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public void setTotalPages(int totalPages) {
        this.totalPages = totalPages;
    }

    public void setUrlPattern(String urlPattern) {
        this.urlPattern = urlPattern;
    }

    @Override
    public int doStartTag() throws JspException {
        try {
            pageContext.getOut().print(createPaginationLinks());
        } catch (IOException e) {
            throw new JspException("Error creating pagination links", e);
        }
        return SKIP_BODY;
    }

    private String createPaginationLinks() {
        StringBuilder sb = new StringBuilder();

        // 首页按钮
        if (currentPage > 1) {
            sb.append("<a href='").append(urlPattern).append("?page=1'>首页</a>");
        }

        // 上一页按钮
        if (currentPage > 1) {
            sb.append("<a href='").append(urlPattern).append("?page=").append(currentPage - 1).append("'>上一页</a>");
        }

        // 分页链接
        int startPage = Math.max(1, currentPage - MAX_VISIBLE_PAGES / 2);
        int endPage = Math.min(totalPages, startPage + MAX_VISIBLE_PAGES - 1);

        // 显示省略号前的部分
        if (startPage > 2) {
            sb.append("<a href='").append(urlPattern).append("?page=1'>1</a>");
            sb.append("<span>...</span>");
        }

        // 显示当前页附近的页码
        for (int i = startPage; i <= endPage; i++) {
            sb.append("<a href='").append(urlPattern).append("?page=").append(i).append("' class='");
            if (i == currentPage) {
                sb.append("active");
            }
            sb.append("'>").append(i).append("</a>");
        }

        // 显示省略号后部分
        if (endPage < totalPages - 1) {
            sb.append("<span>...</span>");
            sb.append("<a href='").append(urlPattern).append("?page=").append(totalPages).append("'>").append(totalPages).append("</a>");
        }

        // 下一页按钮
        if (currentPage < totalPages) {
            sb.append("<a href='").append(urlPattern).append("?page=").append(currentPage + 1).append("'>下一页</a>");
        }

        // 尾页按钮
        if (currentPage < totalPages) {
            sb.append("<a href='").append(urlPattern).append("?page=").append(totalPages).append("'>尾页</a>");
        }

        return sb.toString();
    }
}
